package net.cl.mvc.pagination;

import java.util.List;

public abstract class Pagination implements Pageable {

	private int itemsCount = 0;
	private int pageSize = 10;
	private int currentPage = 1;
	private int lastPage = 0;
	private int startIndex = 0;
	private boolean hasPrevious = true;
	private boolean hasNext = true;

	private List<?> itemList;

	@Override
	public int getCurrentPage() {
		return currentPage;
	}

	@Override
	public int getNumberOfPages() {
		return lastPage;
	}

	@Override
	public int getPreviousPage() {
		return currentPage - 1;
	}

	@Override
	public int getNextPage() {
		return currentPage + 1;
	}

	/**
	 * 取得总记录条数
	 */
	public int getItemsCount() {
		return itemsCount;
	}

	/**
	 * 取得每页多少条数据
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * 取得起始数据索引
	 */
	public int getStartIndex() {
		return startIndex;
	}

	/**
	 * 是否有上一页
	 */
	public boolean hasPrevious() {
		return hasPrevious;
	}

	/**
	 * 是否有下一页
	 */
	public boolean hasNext() {
		return hasNext;
	}

	/**
	 * 取得分页对象集合
	 */
	public List<?> getItems() {
		return itemList;
	}

	/**
	 * 设置总记录条数
	 */
	public void setItems(List<?> itemList) {
		this.itemList = itemList;
	}

	/**
	 * 设置每页多少条数据
	 */
	public void setItemsCount(int itemsCount) {
		this.itemsCount = itemsCount;
		initialize();
	}

	/**
	 * 设置当前页数
	 */
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	/**
	 * 设置分页对象集合
	 */
	public void setCurrentPage(String currentPage) {
		this.currentPage = stringToInt(currentPage);
	}

	private void initialize() {
		lastPage = itemsCount / pageSize;
		if (lastPage % pageSize > 0)
			lastPage++;
		if (currentPage == 1)
			hasPrevious = false;
		if (currentPage == lastPage)
			hasNext = false;
		startIndex = (currentPage - 1) * pageSize;
	}

	/**
	 * 将字符串转为数字<br>
	 * 如果是非法格式，返回1
	 */
	protected int stringToInt(String str) {
		try {
			return Integer.parseInt(str) <= 0 ? 1 : Integer.parseInt(str);
		} catch (NumberFormatException nfe) {
			return 1;
		}
	}

	/**
	 * 转换成页面直接可用的分页代码
	 */
	public abstract String toPageCode(String url);

}
